<template>
    <dev class="page-container">
        <el-row>
          <el-col :span="6">
            <el-input v-model="filterText"
              class="w-60 mb-2"
              placeholder="Filter keyword"
            />
            <el-tree
                style="max-width: 600px"
                :data="data"
                :props="defaultProps"
                @node-click="handleNodeClick"
                :filter-node-method="filterNode"
                :default-expanded-keys="[1]"
                node-key="id"
                ref="treeRef"
            />
          </el-col>
          <el-col :span="18">
            <div>
                <el-row>
                    <el-col :span="20">
                        <div>
                            <el-upload v-if="props.flag==='0'"
                                class="upload-demo"
                                :action="uploadURL+classifyId"
                                :before-upload="handleBefore"
                                :on-success="handleSuccess"
                            >
                                <el-button type="primary">上传图片</el-button>
                            </el-upload>
                        <el-button type="danger" v-if="props.flag==='0'" style="margin-left: 20px;">删除图片</el-button>
                        <el-button type="primary" v-if="props.flag==='1'" @click="selectimageList">选择图片</el-button>
                        <el-tree-select placeholder="图片移至"
                                v-model="goto"
                                :data="data"
                                check-strictly
                                :render-after-expand="false"
                                style="width: 240px;margin-left: 10px;"
                                @node-click="handleClassify"
                            />
                        </div>
                        
                        
                    </el-col>
                    <el-col :span="4">
                        
                    </el-col>
                </el-row>
                <el-row style="margin-top: 20px;">
                  <el-col :span="24">
                      <div style="display: flex;">
                        <div v-for="item in imageList" :key="item.id" >
                          <el-badge :hidden="!item.selected" value="选中" class="item" :offset="[-30, 15]">
                            <el-image style="width: 120px; height: 120px;margin-right: 10px;" :src="imageBase+item.fileName"
                               fit="fill" @click="selectEditImage(item)" />
                          </el-badge>
                        </div>
                      </div>
                  </el-col>
                </el-row>
                <el-pagination size="small" v-model:page="queryParams.pageNum" 
                  v-model:limit="queryParams.pageSize"
                  layout="prev, pager, next" :total="total" 
                  :current-page="currPageCount" @current-change="handleCurrentChange"/>
            </div>
          </el-col>
        </el-row>
    </dev>
</template>

<script setup lang="ts" name="material">
import { defineAsyncComponent, reactive, ref, onMounted,defineProps,watch } from 'vue';
import {materialPageList,updateClassify} from '@/api/goods/matenial'
import { ElMessageBox ,ElMessage  } from 'element-plus';
import { cloneDeep } from 'lodash';

// 定义组件属性-父组件传过来的值
const props = defineProps({
  buttonTop: {
    default: 0,
    type: Number,
  },
  flag:{
    default:'0',
    type: String
  },
  danxuan:{
    default:true,
    type:Boolean
  }
});

const filterText = ref('')
const classifyId = ref('classify=0')
const uploadURL = import.meta.env.BASE_URL +'api/material/upload?'
const imageBase = 'http://localhost:8080/profile/'
const imageList=ref([])
const goto=ref(null)
const radio2 = ref('1')
const total=ref(0)
const currPageCount=ref(0)
const selectImg = ref([])
const treeRef=ref([])
const queryParams=reactive({
  pageSize:30,
  pageNum:1,
  classify:0
})
//树形静态数据
const data = ref([
  {
    label: '全部图片',
    id:0
  },
  {
    label: '商品图片',
    id:1,
    children: [
      {
        label: '分类图片',
        id:2,
      },
      {
        label: '商品图片',
        id:3,
      },
      {
        label: '其他图片',
        id:4,
      },
    ],
  }
])

const emit = defineEmits(['updateValue']);

//点击子组件按钮将数据传递到子组件
function selectimageList(){
  emit("updateValue",selectImg,props.danxuan)
}

watch(filterText, function(val:any) {
  treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}
//设置树形组件层级属性
const defaultProps = {
  children: 'children',
  label: 'label',
}
//选中图片移动到指定的分类
function handleClassify(val:any){
  const classify = val.id
  for(let i =0;i<selectImg.value.length;i++){
    selectImg.value[i].classify=classify
  }
  updateClassify(selectImg.value).then((resp:any)=>{
      if(resp.code==200){
        ElMessage({ message: '提交成功', type: 'success', })
        pageList()
      }
  })
}
//点击树触发
function handleNodeClick(val:any){
    classifyId.value = 'classify='+val.id
    queryParams.classify = val.id
    pageList()
}

//查询素材
function pageList(){
  materialPageList(queryParams).then((resp:any)=>{
    imageList.value = resp.data.records
    total.value = resp.data.total
		currPageCount.value = resp.data.current
  })
}
//点击分页
function handleCurrentChange(val:any){
  queryParams.pageNum = val
  pageList()
}

function handleSuccess(){
  pageList()
}
function handleBefore(file:any){
  const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJPGorPNG) {
        ElMessage({ message: '只支持上传 JPG/PNG 格式的图片!', type: 'error', })
        return false; // 阻止文件上传
      }
      return true; // 允许文件上传
}
function selectNumber(item:any){
    for(let i =0 ;i<selectImg.value.length;i++){
      if(selectImg.value[i].id==item.id){
        console.log(selectImg.value[i].id,item.id)
        return (i+1)
      }
    }
    return null
}
//选中图片
function selectEditImage(item:any){
  for(let i=0;i<imageList.value.length;i++){
    if(imageList.value[i].id==item.id){
      if(!imageList.value[i].selected){
        imageList.value[i].selected=true
      }else{
        imageList.value[i].selected=false
      }
      
    }
  }

  console.log(item)
  selectImg.value.push(item)
  let copy = cloneDeep(selectImg)
  console.log(selectImg.value.length)
  if(selectImg.value.length>1){
    for(let i = 0;i<copy.value.length;i++){
      if(item.id==copy.value[i].id){
        selectImg.value = selectImg.value.filter(obj => obj.id !== item.id)
      }
    }
  }
  console.log(selectImg)
}
//组件加载完成后
onMounted(() => {
	pageList();
});

</script>
<style lang="scss">
.page-container {
    height: 100%;
	background-color: #fff;
    padding: 10px 10px;
    display: flex;
    flex-direction: column;
    .pageContent {
        height: calc(100% - 140px);
        flex: 1;
    }
}
.upload-demo{
  width: 80px;
  display: inline-flex;
}
.el-upload-list{
  display: none;
}
</style>